use rusqlite::{Connection, Result};
use dirs;
use log::{error, info};
use crate::database;

/// 初始化数据库连接池
/// 
/// # 返回结果
/// * `Result<(), Box<dyn std::error::Error>>`   成功则返回Ok(()), 否则返回Err(Box<dyn std::error::Error>)
/// * `Box<dyn std::error::Error>`               失败则返回错误信息
pub fn setup_database() -> std::result::Result<(), Box<dyn std::error::Error>> {
    info!("正在初始化数据库...");

    database::init_db().map_err(|e| {
        let data_dir = dirs::data_dir()
            .map(|path| path.join("charts-manager").display().to_string())
            .unwrap_or_else(|| "未知路径".to_string());

        error!("数据库初始化失败: {}，路径: {}", e, data_dir);
        e
    })?;

    info!("数据库初始化成功");
    Ok(())
}

/// 初始化数据库
///
/// # 返回结果
/// * `Result<Connection, String>`   成功则返回Ok(App), 失败则返回Err(String)
pub fn init_db() -> Result<Connection, String> {
    let data_dir = dirs::data_dir().ok_or("无法获取数据目录".to_string())?;
    let db_dir = data_dir.join("charts-manager");
    let db_path = db_dir.join("apps.db");

    // 确保目录存在
    std::fs::create_dir_all(&db_dir)
        .map_err(|e| format!("创建目录失败: {} (路径: {:?})", e, db_dir))?;

    Connection::open(&db_path)
        .map_err(|e| format!("数据库连接失败: {} (路径: {:?})", e, db_path))
        .and_then(|conn| {
            // 存放地址为: /Users/xincan/Library/Application Support/charts-manager
            // conn.execute("DROP TABLE IF EXISTS apps", [])
            //     .map_err(|e| format!("表删除失败: {}", e))?;
            conn.execute(
                "CREATE TABLE IF NOT EXISTS apps (
                id TEXT NOT NULL CHECK(length(id) <= 20) PRIMARY KEY,
                name TEXT NOT NULL CHECK(length(name) <= 20),
                url TEXT NOT NULL CHECK(length(url) <= 500),
                icon TEXT NOT NULL CHECK(length(icon) <= 20),
                description TEXT CHECK(length(description) <= 1000)
            )", []
            ).map_err(|e| format!("表创建失败: {}", e))?;
            Ok(conn)
        })
}
